import React, { useState, useEffect, useRef } from 'react'
import { View } from '@tarojs/components'
import { ITouchEvent } from '@tarojs/components/types/common'
import cx from 'classnames'
import dayjs from 'dayjs'

import './index.scss'

interface BottomPanelProps {
  showPanel: boolean
  closeOnClickOverlay?: boolean
  doNotRenderContentWhenHide?: boolean
  onClose?: () => void
  className?: string
  style?: React.CSSProperties
  children: any
  keepTouch?: boolean
}

export const BottomPanel = ({
  showPanel,
  closeOnClickOverlay = true,
  children,
  onClose,
  doNotRenderContentWhenHide = true,
  className,
  style,
  keepTouch
}: BottomPanelProps) => {
  const [isShowPanel, setIsShowPanel] = useState(showPanel)
  const timerRef = useRef(0)

  useEffect(() => {
    if (showPanel) {
      timerRef.current = dayjs().valueOf()
    }
    setIsShowPanel(showPanel)
  }, [showPanel])

  const onModelClick = (e: ITouchEvent) => {
    e.stopPropagation()

    if (closeOnClickOverlay && dayjs().valueOf() - timerRef.current >= 500) {
      setIsShowPanel(false)
      onClose?.()
    }
  }

  const onTouchMove = (e: ITouchEvent) => {
    e.stopPropagation()
  }

  const onPanelClick = (e: ITouchEvent) => {
    e.stopPropagation()
  }

  if (!isShowPanel && doNotRenderContentWhenHide) {
    return null
  }

  return (
    <View
      className={cx('modal-wrap-bottom-panel', { 'modal-wrap-bottom-panel__open': isShowPanel })}
      onClick={onModelClick}
      onTouchMove={keepTouch ? undefined : onTouchMove}
      catchMove={!keepTouch}
    >
      <View className={cx('modal-content-bottom-panel-wrap', className)} onClick={onPanelClick} style={style}>
        {children}
      </View>
    </View>
  )
}
